/*
 * VentanaNuevaMusica.java
 *
 * Created on 23 de septiembre de 2008, 23:46
 */

package vista;

//import controlador.ControladorAlta;
//import controlador.ControladorConsulta;
//import datos.Modificacion;
import java.awt.Dimension;
import java.awt.Toolkit;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
//import java.util.Iterator;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JOptionPane;
import javax.swing.table.DefaultTableModel;
import javax.swing.table.TableColumn;
import dominio.Cancion;
import servicios.player.media.helliker.id3.ID3v2FormatException;
import servicios.player.media.helliker.id3.MP3File;
import servicios.player.media.helliker.id3.NoMPEGFramesException;
import vista.util.Utils;
import vista.util.VentanaNuevaMusicaUtil;

/**
 *
 * @author  marcelo
 */
public class VentanaNuevaMusica extends javax.swing.JFrame 
{
    private Collection musicas = new ArrayList();
    private boolean seleccionado = false;
    private VentanaNuevaMusicaUtil util = new VentanaNuevaMusicaUtil(this);
    private VentanaAgregarTema ventana;
    private boolean origen;
    

    /** Creates new form VentanaNuevaMusica */
    public VentanaNuevaMusica() {
        initComponents();
        this.inicializar();
        origen = false;
    }

    public VentanaNuevaMusica(VentanaAgregarTema ventana)
    {
        initComponents();
        this.inicializar();
        this.ventana = ventana;
        origen = true;
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jScrollPane1 = new javax.swing.JScrollPane();
        jTableCanales = new javax.swing.JTable();
        jLabel1 = new javax.swing.JLabel();
        jTextFieldGenero = new javax.swing.JTextField();
        jButtonGuardar = new javax.swing.JButton();
        jButtonSalir = new javax.swing.JButton();
        jTextFieldNombre = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        jButtonModificar = new javax.swing.JButton();
        jButtonExaminar = new javax.swing.JButton();
        jTextFieldPathCancion = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jTextFieldArtista = new javax.swing.JTextField();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("Nuevo Genero Musical");

        jTableCanales.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Codigo", "Nombre", "Genero"
            }
        ) {
            boolean[] canEdit = new boolean [] {
                false, false, false
            };

            public boolean isCellEditable(int rowIndex, int columnIndex) {
                return canEdit [columnIndex];
            }
        });
        jTableCanales.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                jTableCanalesMouseClicked(evt);
            }
        });
        jTableCanales.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyPressed(java.awt.event.KeyEvent evt) {
                jTableCanalesKeyPressed(evt);
            }
            public void keyReleased(java.awt.event.KeyEvent evt) {
                jTableCanalesKeyReleased(evt);
            }
            public void keyTyped(java.awt.event.KeyEvent evt) {
                jTableCanalesKeyTyped(evt);
            }
        });
        jScrollPane1.setViewportView(jTableCanales);

        jLabel1.setBackground(new java.awt.Color(255, 255, 204));
        jLabel1.setText("Genero");
        jLabel1.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabel1.setOpaque(true);

        jTextFieldGenero.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldGeneroActionPerformed(evt);
            }
        });

        jButtonGuardar.setText("Guardar");
        jButtonGuardar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonGuardarActionPerformed(evt);
            }
        });

        jButtonSalir.setText("Salir");
        jButtonSalir.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonSalirActionPerformed(evt);
            }
        });

        jTextFieldNombre.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldNombreActionPerformed(evt);
            }
        });

        jLabel2.setBackground(new java.awt.Color(255, 255, 204));
        jLabel2.setText("Nombre");
        jLabel2.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabel2.setOpaque(true);

        jButtonModificar.setText("Modificar");
        jButtonModificar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonModificarActionPerformed(evt);
            }
        });

        jButtonExaminar.setText("Examinar");
        jButtonExaminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jButtonExaminarActionPerformed(evt);
            }
        });

        jTextFieldPathCancion.setEditable(false);
        jTextFieldPathCancion.setDisabledTextColor(new java.awt.Color(255, 255, 255));
        jTextFieldPathCancion.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldPathCancionActionPerformed(evt);
            }
        });

        jLabel3.setBackground(new java.awt.Color(255, 255, 204));
        jLabel3.setText("Artista");
        jLabel3.setBorder(javax.swing.BorderFactory.createEtchedBorder());
        jLabel3.setOpaque(true);

        jTextFieldArtista.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jTextFieldArtistaActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 360, Short.MAX_VALUE)
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jButtonGuardar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addGap(39, 39, 39)
                        .addComponent(jButtonModificar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 51, Short.MAX_VALUE)
                        .addComponent(jButtonSalir, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addGap(28, 28, 28)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldGenero, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 60, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(jTextFieldArtista, javax.swing.GroupLayout.PREFERRED_SIZE, 190, javax.swing.GroupLayout.PREFERRED_SIZE))))
                    .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup()
                        .addComponent(jButtonExaminar, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jTextFieldPathCancion, javax.swing.GroupLayout.DEFAULT_SIZE, 264, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 237, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonExaminar)
                    .addComponent(jTextFieldPathCancion, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jTextFieldGenero, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel2, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldNombre, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jLabel3, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jTextFieldArtista, javax.swing.GroupLayout.PREFERRED_SIZE, 22, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 12, Short.MAX_VALUE)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(jButtonGuardar)
                    .addComponent(jButtonSalir)
                    .addComponent(jButtonModificar))
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

private void jButtonSalirActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonSalirActionPerformed
// TODO add your handling code here:
    if(origen)
        this.ventana.llenarTabla();
    this.dispose();
}//GEN-LAST:event_jButtonSalirActionPerformed

private void jTextFieldGeneroActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jTextFieldGeneroActionPerformed
// TODO add your handling code here:
}//GEN-LAST:event_jTextFieldGeneroActionPerformed

private void jButtonGuardarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jButtonGuardarActionPerformed
// TODO add your handling code here:
    this.guardar();
}//GEN-LAST:event_jButtonGuardarActionPerformed

/**
 * Al presionar una tecla, si esta no es la tecla Enter, el sistema va guardando el numero de fila sobre la que se presiono la tecla.
 * Cuando se presiona la tecla Enter, se llama al metodo de modificar y se pasa como parametro el valor de la fila sobre
 * la que se hizo la ultima modificacion.
 * @param evt tecla que fue presionada
 */
private void jTableCanalesKeyReleased(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTableCanalesKeyReleased
}//GEN-LAST:event_jTableCanalesKeyReleased

private void jTableCanalesKeyPressed(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTableCanalesKeyPressed
// TODO add your handling code here:
    if(evt.getKeyCode() == 127)
        this.eliminar();
}//GEN-LAST:event_jTableCanalesKeyPressed

private void jTableCanalesKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_jTableCanalesKeyTyped
// TODO add your handling code here:
    
}//GEN-LAST:event_jTableCanalesKeyTyped

private void jTextFieldNombreActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jTextFieldNombreActionPerformed
{//GEN-HEADEREND:event_jTextFieldNombreActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_jTextFieldNombreActionPerformed

private void jButtonModificarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonModificarActionPerformed
{//GEN-HEADEREND:event_jButtonModificarActionPerformed
    // TODO add your handling code here:
    this.modificar();
}//GEN-LAST:event_jButtonModificarActionPerformed

private void jTableCanalesMouseClicked(java.awt.event.MouseEvent evt)//GEN-FIRST:event_jTableCanalesMouseClicked
{//GEN-HEADEREND:event_jTableCanalesMouseClicked
    // TODO add your handling code here:
    this.seleccionado = true;
    this.seleccionarFila();
}//GEN-LAST:event_jTableCanalesMouseClicked

private void jButtonExaminarActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jButtonExaminarActionPerformed
{//GEN-HEADEREND:event_jButtonExaminarActionPerformed
    // TODO add your handling code here:
    this.cargarTema();
}//GEN-LAST:event_jButtonExaminarActionPerformed

private void jTextFieldPathCancionActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jTextFieldPathCancionActionPerformed
{//GEN-HEADEREND:event_jTextFieldPathCancionActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_jTextFieldPathCancionActionPerformed

private void jTextFieldArtistaActionPerformed(java.awt.event.ActionEvent evt)//GEN-FIRST:event_jTextFieldArtistaActionPerformed
{//GEN-HEADEREND:event_jTextFieldArtistaActionPerformed
    // TODO add your handling code here:
}//GEN-LAST:event_jTextFieldArtistaActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new VentanaNuevaMusica().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton jButtonExaminar;
    private javax.swing.JButton jButtonGuardar;
    private javax.swing.JButton jButtonModificar;
    private javax.swing.JButton jButtonSalir;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTableCanales;
    private javax.swing.JTextField jTextFieldArtista;
    private javax.swing.JTextField jTextFieldGenero;
    private javax.swing.JTextField jTextFieldNombre;
    private javax.swing.JTextField jTextFieldPathCancion;
    // End of variables declaration//GEN-END:variables

    private void inicializar()
    {
        this.centrar();
        this.ajustarTamanioColumna();
        this.limpiar();
        this.cargarTabla();
    }
    
    /**
     * Metodo que trae datos de la base de datos y los carga en el grid.
     */
    private void cargarTabla()
    {
        this.musicas = this.util.traerTodos(this.jTableCanales, this.musicas);
    }
    
    /**
     * Metodo para limpiar los registros de la tabla.
     * Quita todas las filas de la tabla.
     */
    private void limpiar()
    {
        DefaultTableModel modelo = (DefaultTableModel)this.jTableCanales.getModel();
        while(this.jTableCanales.getRowCount() != 0)
                modelo.removeRow(0);
        modelo = null;
    }
    
    private void centrar()
    {
        Dimension pantalla, cuadro;
	pantalla = Toolkit.getDefaultToolkit().getScreenSize();
	cuadro = this.getSize();
	this.setLocation(((pantalla.width - cuadro.width)/2), (pantalla.height - cuadro.height)/2);
    }
    
    private void ajustarTamanioColumna()
    {
        TableColumn column = null;
        for (int i = 0; i < 2; i++) 
        {
            column = jTableCanales.getColumnModel().getColumn(i);
            switch(i)
            {
                case 0:
                        column.setPreferredWidth(15);
                        break;
                case 1:
                        column.setPreferredWidth(103);
                        break;
                case 2:
                        column.setPreferredWidth(103);
                        break;
            }
        }
    }
    
    private boolean verificaBlancos(){
        boolean bandera = true;
        String var;
        var = this.jTextFieldNombre.getText();
        if (var.trim().length()==0)
            bandera = false;
        if(this.jTextFieldGenero.getText().trim().length() == 0)
            bandera = false;
        if(this.jTextFieldPathCancion.getText().trim().length() == 0)
            bandera = false;
        if(this.jTextFieldArtista.getText().trim().length() == 0)
            bandera = false;
        return bandera;   
    }
    
    /**
     * este metodo se encarga de guardar el nuevo estilo de musica ingresado por el usuario.
     * Basicamente comprende 2 procesos:
     * 1)_ Controlar que todos los campos solicitados esten cargados.
     * 2)_ Guardar el nuevo registro.
     */
    private void guardar ()
    {
        if (this.verificaBlancos()) // verifica si todos los campos estan cargados
        {
            Cancion m = new Cancion();
            m.setGenero(this.jTextFieldGenero.getText().trim().toUpperCase());
            m.setNombre(this.jTextFieldNombre.getText().trim().toUpperCase());
            m.setArtista(this.jTextFieldArtista.getText().trim().toUpperCase());
            m.setPath(this.jTextFieldPathCancion.getText().trim().toUpperCase());
            this.util.nuevaMusica(m);
            this.jTextFieldNombre.setText("");
            this.jTextFieldGenero.setText("");
            this.jTextFieldArtista.setText("");
            this.jTextFieldPathCancion.setText("");
            this.jTextFieldGenero.requestFocus();
            this.limpiar();
            this.cargarTabla();
        }
        else 
            JOptionPane.showMessageDialog(null, "Asegurese de que los campos esten llenos","Hay campos en blancos",JOptionPane.ERROR_MESSAGE);
    }

    private void modificar()
    {
        if(this.verificaBlancos() && this.seleccionado)
        {
            this.util.modificarMusica(this.getMusica());
            this.jTextFieldNombre.setText("");
            this.jTextFieldGenero.setText("");
            this.jTextFieldArtista.setText("");
            this.jTextFieldPathCancion.setText("");
            this.jTextFieldGenero.requestFocus();
            this.limpiar();
            this.cargarTabla();
        }
        else
            JOptionPane.showMessageDialog(null, "Debe seleccionar un tema para modificar","No hay tema selecionado",JOptionPane.ERROR_MESSAGE);
    }
    
    ///////////////////////////////// mostrar datos seleccionados del grid

    private void seleccionarFila()
    {
        this.jTextFieldGenero.setText(String.valueOf(this.jTableCanales.getValueAt(this.jTableCanales.getSelectedRow(), 2)));
        this.jTextFieldNombre.setText(String.valueOf(this.jTableCanales.getValueAt(this.jTableCanales.getSelectedRow(), 1)));
    }

    private void eliminar()
    {
            this.util.eliminarMusica(this.getMusica());
            this.jTextFieldNombre.setText("");
            this.jTextFieldGenero.setText("");
            this.jTextFieldGenero.requestFocus();
            this.limpiar();
            this.cargarTabla();
    }

    private Cancion getMusica()
    {
        int codigo = Integer.parseInt(String.valueOf(this.jTableCanales.getValueAt(this.jTableCanales.getSelectedRow(), 0)));
        Cancion m = new Cancion();
        m.setCodigo(codigo);
        m.setGenero(this.jTextFieldGenero.getText().trim().toUpperCase());
        m.setNombre(this.jTextFieldNombre.getText().trim().toUpperCase());
        m.setArtista(this.jTextFieldArtista.getText().trim().toUpperCase());
        m.setPath(this.jTextFieldPathCancion.getText().trim().toUpperCase());
        return m;
    }


    private void cargarTema()
    {
        this.jTextFieldPathCancion.setText(this.util.cargarTema());
        try
        {
            MP3File mp3File = new MP3File(this.jTextFieldPathCancion.getText().trim());
            this.jTextFieldNombre.setText(mp3File.getTitle().trim());
            this.jTextFieldGenero.setText(mp3File.getGenre());
            this.jTextFieldArtista.setText(mp3File.getArtist());
            //        System.out.println(u.reemplazarAzterisco(this.jTextFieldPathCancion.getText().trim()));
            //        System.out.println(u.reemplazarAzterisco(this.jTextFieldPathCancion.getText().trim()));
        } catch (FileNotFoundException ex)
        {
            Logger.getLogger(VentanaNuevaMusica.class.getName()).log(Level.SEVERE, null, ex);
        } catch (NoMPEGFramesException ex)
        {
            Logger.getLogger(VentanaNuevaMusica.class.getName()).log(Level.SEVERE, null, ex);
        } catch (IOException ex)
        {
            Logger.getLogger(VentanaNuevaMusica.class.getName()).log(Level.SEVERE, null, ex);
        } catch (ID3v2FormatException ex)
        {
            Logger.getLogger(VentanaNuevaMusica.class.getName()).log(Level.SEVERE, null, ex);
        }
    }

}
